const querystring = require("querystring"); // 用于解析URL中的查询字符串
const handleBlogRouter = require("./src/router/blog");
const handleUserRouter = require("./src/router/user");
const {
  getCookieExpires, // 设置Cookie的过期时间
  generateRandomID, // 生成随机ID
} = require("./src/utils");
const { get, set } = require("./src/db/redis");
const { access } = require("./src/utils/log");

// 解析日志
const analyzeLog = (req) => {
  const log = `${req.method} -- ${req.url} -- ${req.headers["user-agent"]} -- ${Date.now()}`;
  access(log); // 记录日志
};
// 解析路径
const analyzeUrl = (req) => {
  const url = req.url;
  req.path = url.split("?")[0]; // 路径
  req.query = querystring.parse(url.split("?")[1]); // 查询字符串转换对象形式
};
// 解析 cookie
const analyzeCookie = (req) => {
  req.cookie = {};
  const cookieStr = req.headers.cookie || ""; // k1=v1;k2=v2 结构化格式
  cookieStr.split(";").forEach((item) => {
    if (!item) return;
    const arr = item.split("="); // 拆分 = 号
    const key = arr[0]?.trim();
    const val = arr[1]?.trim();
    req.cookie[key] = val; // 设置 cookie
  });
};
// 解析 Body
const analyzeBody = (req) => {
  return new Promise((resolve) => {
    if (req.method !== "POST" || req.headers["content-type"] !== "application/json") {
      resolve({});
      return;
    }
    let postData = "";
    req.on("data", (chunk) => {
      postData += chunk.toString();
    });
    req.on("end", () => {
      if (!postData) {
        resolve({});
        return;
      }
      resolve(JSON.parse(postData));
    });
  });
};
// 解析 session
const analyzeSession = (req, res) => {
  let userId = req.cookie?.userid;
  if (!userId) {
    userId = generateRandomID(10); // 生成随机用户 id
    set(userId, {}); // 初始化（假设用户直接进入登录页）
    // path=/ 失效路由 不然其他路由会失效
    // httpOnly 只允许后端修改 document.cookie = xx 无法生效
    // expires 设置过期时间
    res.setHeader("Set-Cookie", `userid=${userId}; path=/; httpOnly; expires=${getCookieExpires()}`);
  }
  req.sessionId = userId; // 设置 session id
  // 异步获取 redis
  return get(userId).then((sessionData) => {
    req.session = sessionData || {}; // session 储存用户信息
    return analyzeBody(req);
  });
};
// 404
const createError = (res) => {
  res.writeHead(404, {
    "Content-type": "text/plain", // 纯文本
  });
  res.write("404 Not Found\n");
  res.end();
};
// 入口
const serverHandle = (req, res) => {
  analyzeLog(req); // 解析日志
  analyzeUrl(req); // 解析 url
  analyzeCookie(req); // 解析 cookie
  // 解析 session
  analyzeSession(req, res).then((bodyData) => {
    req.body = bodyData; // 设置 body
    res.setHeader("Content-type", "application/json"); // 设置返回格式
    const blogResult = handleBlogRouter(req, res); // 博客路由
    if (blogResult) {
      blogResult.then((blogData) => {
        res.end(JSON.stringify(blogData));
      });
      return;
    }
    const userResult = handleUserRouter(req, res); // 用户路由
    if (userResult) {
      userResult.then((userData) => {
        res.end(JSON.stringify(userData));
      });
      return;
    }
    createError(res); // 未命中
  });
};
module.exports = serverHandle;
